package com.poulpicious.ethanj.states;

import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;

import com.poulpicious.ethanj.util.GameData;
import com.poulpicious.ethanj.util.ResourceLoader;

public class SplashScreenState extends BasicGameState {

	private Image logo;
	private int elapsedTime = 0;
	private int delay = 2000;
	private boolean loading;
	private String loadingMessage;
	
	@Override
	public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
		logo = new Image("res/images/splash_logo.png");
		
		ResourceLoader.preloadImage("logo", "splash_logo.png");
	}

	@Override
	public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
		int halfWidth = GameData.WIDTH / 2;
		int halfHeight = GameData.HEIGHT / 2;
		g.setColor(Color.white);
		g.fillRect(0, 0, GameData.WIDTH, GameData.HEIGHT);
		logo.draw(halfWidth - logo.getWidth() / 2, halfHeight - logo.getHeight() / 2);
		
		if (loading) {
			g.setColor(Color.black);
			g.drawString(loadingMessage, halfWidth - 400 / 2, 480);
			g.drawRect(halfWidth - 400 / 2, 500, 400, 30);
			g.fillRect(halfWidth - 400 / 2, 500, 400 * ResourceLoader.getPercentage(), 30);
		}
	}

	@Override
	public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
		if (!loading) {
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			loading = true;
		}
		if (ResourceLoader.hasNext()) {
			loadingMessage = ResourceLoader.getState();
			ResourceLoader.loadNextResource();
			elapsedTime += delta;
			if (elapsedTime > delay) {
				MainMenuState mms = new MainMenuState();
				sbg.addState(mms);
				sbg.enterState(mms.getID());
			}
		} else {
			loadingMessage = "Failed to load data...";
		}
	}

	@Override
	public int getID() {
		return GameData.SPLASH_SCREEN;
	}

}
